package com.levi.mall.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.levi.enums.EnumUtil;
import com.levi.mall.mapper.ProductMapper;
import com.levi.mall.service.CategoryService;
import com.levi.mall.service.ProductService;
import com.levi.pojo.Product;
import com.levi.utils.BeanConvertUtil;
import com.levi.vo.ProductDetailVo;
import com.levi.vo.ProductVo;
import com.levi.vo.ResponseVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * @author shentong
 * @since 2022/3/29 9:33 PM
 */
@Service
@Slf4j
public class ProductServiceImpl extends ServiceImpl<ProductMapper, Product>
        implements ProductService {

    @Autowired
    private CategoryService categoryService;

    @Override
    public ResponseVo<PageInfo<ProductVo>> getList(Integer categoryId, Integer pageNum, Integer pageSize) {
        Set<Integer> categoryIdSet = new HashSet<>();
        if (categoryId != null) {
            categoryService.findSubCategoryId(categoryId,categoryIdSet);
            categoryIdSet.add(categoryId);
        }
        PageHelper.startPage(pageNum, pageSize);
        List<Product> products = baseMapper.selectByCategoryIdSet(categoryIdSet);
        List<ProductVo> productVos = BeanConvertUtil.listConvert(products, ProductVo.class);
        log.info("productVos =>{}",productVos);
        PageInfo<ProductVo> pageInfo = new PageInfo<>(productVos);

        return ResponseVo.success(pageInfo);
    }

    @Override
    public ResponseVo<ProductDetailVo> getInfo(Integer productId) {
        Product product = this.getById(productId);
        if (EnumUtil.PRODUCT_STATUS_SOLD_OUT.getCode().equals(product.getStatus()) || EnumUtil.PRODUCT_STATUS_DELETED.getCode().equals(product.getStatus())) {
            return ResponseVo.error(EnumUtil.PRODUCT_SOLD_OUT_OR_DELETED);
        }
        ProductDetailVo productDetailVo = new ProductDetailVo();
        BeanUtils.copyProperties(product, productDetailVo);
        productDetailVo.setStock(productDetailVo.getStock() > 100 ? 100 : productDetailVo.getStock());
        return ResponseVo.success(productDetailVo);
    }


    @Override
    public ResponseVo<PageInfo<ProductVo>> allProducts(Integer pageNum, Integer pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        List<Product> productList = this.list();
        List<ProductVo> productVos = BeanConvertUtil.listConvert(productList, ProductVo.class);
        PageInfo<ProductVo> productVoPageInfo = new PageInfo<>(productVos);
        return ResponseVo.success(productVoPageInfo);
    }
}
